package com.example.myapplication.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableRow;

import androidx.annotation.ColorLong;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.myapplication.ImgInfo.BasInfo;
import com.example.myapplication.ImgInfo.PunishInfo;
import com.example.myapplication.R;
import com.example.myapplication.utils.HttpUtils;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.renderer.XAxisRenderer;
import com.github.mikephil.charting.renderer.YAxisRenderer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ShopFragment extends Fragment {
    private View view;
    private Button btn;
    private LineChart lineChart;
    private PieChart pieChart;
    private BarChart barChart;
    private DecimalFormat df = new DecimalFormat("#.##");
    private Map<String, Integer> map1 = new HashMap<>();
    private Map<String, Integer> map2 = new TreeMap<>();
    private Map<String, Integer> map3 = new TreeMap<>();
    private String[] name ;
    int year = 0;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    ShowPie();
                    ShowLine();
                    break;
                case 300:
                    ShowBar();
                    break;
                default:
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_shop, container, false);
        InitView(view);
        GetData();
        return view;
    }

    private void InitView(View view) {
        btn=view.findViewById(R.id.btn);
        lineChart = view.findViewById(R.id.my_line_chart);
        pieChart = view.findViewById(R.id.my_pie_chart);
        barChart = view.findViewById(R.id.my_bar_chart);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(),BarTextActivity.class);
                startActivity(intent);
            }
        });
    }

    private void ShowLine() {
        //无数据显示
        lineChart.setNoDataText("当前无数据");
        //
        List<Entry> list = new ArrayList<>();
        for (String k : map2.keySet()) {
            year = Integer.parseInt(k);
            list.add(new Entry(year, map2.get(k)));
        }
        //内容
        //线段数据实例
        LineDataSet lineDataSet = new LineDataSet(list, "各年份违规折线图");
        //线段数据填充
        LineData data = new LineData(lineDataSet);
//        List<ILineDataSet> lineDataSets = new ArrayList<ILineDataSet>();
//        lineDataSets.add(lineDataSet);
//        多条线段所有
//        lineChart.setXAxisRenderer(new XAxisRenderer());
        lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float v, AxisBase axisBase) {
                return String.valueOf((int) v);
            }
        });
        lineChart.getXAxis().setLabelCount(list.size());
        lineChart.getXAxis().setGranularity(1);
        lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        //填充数据
        lineChart.setData(data);
        //开始绘制
        lineChart.invalidate();
    }

    private void GetData() {
        //交通违规数据加载
        HttpUtils.Get("http://192.168.100.147:8080/skill/system/punishments", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String data = response.body().string();
                List<PunishInfo.Pun> list = new Gson().fromJson(data, new TypeToken<List<PunishInfo.Pun>>() {
                }.getType());
                //遍历数组  map集合处理数据
//                for (int i = 0; i < list.size(); i++) {
                for (PunishInfo.Pun k : list) {
                    String type = k.getReason();
                    if (map1.containsKey(type)) {
                        int num = map1.get(type);
                        num++;
                        map1.put(type, num);
                    } else {
                        map1.put(type, 1);
                    }
                }
                for (PunishInfo.Pun kk : list) {
                    String times = kk.getTime();
                    //截取字符获取年份
                    String time = times.substring(0, 4);
                    if (map2.containsKey(time)) {
                        int numm = map2.get(time);
                        numm++;
                        map2.put(time, numm);
                    } else {
                        map2.put(time, 1);
                    }
                }
//                }
                handler.sendEmptyMessage(200);

            }
        });

        //巴士数据加载
        HttpUtils.Get("http://192.168.100.147:8080/skill/userinfo/orderlist?pageNum=1&pageSize=2&userId=4", new Callback() {
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String data = response.body().string();
                BasInfo basInfo = new Gson().fromJson(data,BasInfo.class);
                for (int i =0;i<basInfo.getRows().size();i++) {
                    String name = basInfo.getRows().get(i).getUserName();
                        if (map3.containsKey(name)) {
                            int num = map3.get(name);
                            num++;
                            map3.put(name, num);
                        } else {
                            map3.put(name, 1);
                        }
                }
                handler.sendEmptyMessage(300);
            }
        });

    }

    private void ShowPie() {
        pieChart.setNoDataText("当前无数据");
        //内圆取消
        pieChart.setDrawHoleEnabled(false);
        //标题取消
        pieChart.getDescription().setEnabled(false);
        //填充数据
        List<PieEntry> list = new ArrayList<>();
        for (String k : map1.keySet()) {
            list.add(new PieEntry(map1.get(k), k));
        }
        PieDataSet dataSet = new PieDataSet(list, "饼图");
        //颜色 字体
        dataSet.setColors(Color.RED,Color.GRAY,Color.BLACK,Color.WHITE,Color.YELLOW);
        dataSet.setValueTextColor(Color.DKGRAY);
        dataSet.setValueTextSize(20);
        //填充绘制
        PieData pieData = new PieData(dataSet);
        pieChart.setData(pieData);
        pieChart.invalidate();
    }

    private void ShowBar() {
        barChart.setNoDataText("没有数据");
        List<BarEntry> list = new ArrayList<>();
        int num = 0;
        name = new String[map3.size()];
        for(String k:map3.keySet()){
            name[num] = k;
            list.add(new BarEntry(++num,map3.get(k)));
        }
        BarDataSet barDataSet = new BarDataSet(list,"出行总数");
        BarData barData = new BarData(barDataSet);
        barChart.getXAxis().setLabelCount(list.size());
        barChart.getXAxis().setGranularity(1);
        barChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        barChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float v, AxisBase axisBase) {
                return name[(int)v-1];
            }
        });
        barData.setBarWidth(0.3f);
        barChart.setPadding(2,2,2,2);
        barChart.setData(barData);
        barChart.invalidate();
    }

}
